const Router = require('koa-router');
const tool = require("../../tools/tool");
const router = new Router();
const {db, Op, QueryTypes} = require("../../models/db");
const tools = require("../../tools/tool");
// 查询收款票据-手机-新增收款中查询单据
router.post('/ldsk/getSkBill', async ctx => {
    let body = ctx.request.body
    let tenantId = ctx.user.tenantId
    let currentPage = body.currentPage
    let pageSize = 20
    let skip = (currentPage - 1) * pageSize
    let uid = ctx.user.id
    let formData = body.formData
    let where = ``
    if(formData.mybill) {
        where += ` and a.salesId=${uid} `
    }
    if(formData.buName) {
        where += ` and b.name like '%${formData.buName}%' `
    }
    if(formData.endDate) {
        where += ` and a.billDate<='${formData.endDate}' `
    }
    let sql = `
        select id, billId, tenantId, srcBillNo, srcBillDate, srcTransType, srcTransTypeName, buId, buName, 
               billState, billType, salesId, salesName, arrears, hxAmount,(arrears-hxAmount) leftAmount, (arrears-hxAmount) nowCheck, 0 yhAmount 
        from 
         (
            select a.id,
                                a.id billId,
                                a.tenantId,
                                a.billNo srcBillNo,
                                a.billDate srcBillDate,
                                a.transType srcTransType,
                                a.transTypeName srcTransTypeName,
                                a.buId,b.name buName,
                                a.billState,
                                a.billType,
                                a.salesId, c.name salesName,
                                case when a.transType = 150602 then -isnull(a.arrears,0) else isnull(a.arrears,0) end arrears,
                                isnull(a.hxAmount,0) hxAmount
                         from invoice a
            inner join contact b on a.buId=b.id and a.tenantId=${tenantId} and a.billType='SALE' and a.billState='accounted' ${where} 
            left join admin c on a.salesId=c.id 
        ) a where (arrears-hxAmount) <> 0 
    `
    let totalsql = `select count(*) total from (${sql}) a  `
    let total = await db.query(totalsql, {type: QueryTypes.SELECT, plain: true})
    let ret = await db.query(sql + ` order by buId,billState asc offset ${skip} row fetch next ${pageSize} rows only;`, {type: QueryTypes.SELECT})
    return ctx.suc('', {
        total: total.total,
        list: ret
    })
})





module.exports = router;